import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { emitter } from "@/utils/mitt";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from 'vue-router';
import {
  SecuritiesClientGetSecurityClients,
  SecuritiesClientGetClientBaseData,
  SecuritiesClientCreateSecuritiesClientBase,
  SecuritiesClientGetSecuritiesConditionDataById
} from "@/api/stu/Cecurity";
import { type PaginationProps } from "@pureadmin/table";
import qs from 'qs';
export function useCustomerAnalysis() {
  const RefCustomerGroup = ref();
  const Visible = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const MySignIn = ref("all");
  const RefScreenPerson = ref();
  const SetMyJSonar = ref();// 保存子组件内容
  const dataList = ref([]);
  const riskGrade = ref("");
  const route = useRoute()
  const SelectCustomerBase = ref();
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "name",
    },
    {
      label: "性别",
      prop: "sex",
      cellRenderer: ({ row }) => (
        <span>
          {
            row.sex === 0 ? "男" : "女"
          }
        </span>
      )
    },
    {
      label: "年龄",
      prop: "age",
    }, {
      label: "教育程度",
      prop: "educationLevel",
    },
    {
      label: "收入来源",
      prop: "incomeSource",
    },
    {
      label: "投资比例",
      prop: "investmentRatio",
    },
    {
      label: "用于投资的资产数额",
      prop: "investAmount",
      width: 150
    },

    {
      label: "数额较大债务",
      prop: "largeAmountDebt",
    },
    {
      label: "投资知识",
      prop: "investmentKnowledge",
    }, {
      label: "投资经验",
      prop: "investmentExperience",
    },
    {
      label: "产品偏好",
      prop: "productPreferences",
    }, {
      label: "投资期限",
      prop: "investmentTerm",
    },
    {
      label: "策略偏好",
      prop: "strategicPreferences",
    }, {
      label: "风险偏好",
      prop: "riskPreferences",
    },
  ];
  const CustomerGroup = reactive({
    name: "",
    SignIn: ""
  })

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });

  const BtnLoading = ref<boolean>(false)

  // 查询
  emitter.on('EmitCustomerGroup', (row) => {
    SetMyJSonar.value = row
    getListData(SetMyJSonar.value)
  })


  // 创建客户群 -- 窗口
  emitter.on('EM_openVisible', async (row) => {
    SetMyJSonar.value = eval(row.value)
    Visible.value = true;
  })


  // 创建客户群
  function getCustomerGroup(RefCustomerGroup: FormInstance | undefined) {
    (RefCustomerGroup as any).validate(async valid => {
      if (!valid) return;
      const data = {
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        pageIndex: pagination.currentPage,
        pageCount: pagination.pageSize,
        conditionsStr: SetMyJSonar.value || [],
        clientBaseName: CustomerGroup.name,
        riskGrade: CustomerGroup.SignIn
      };
      BtnLoading.value = true
      const res = await SecuritiesClientCreateSecuritiesClientBase(data);
      if (res.success) {
        ElMessage.success(res.msg);
        HideVisible(RefCustomerGroup);
        getClientBaseData();
        emitter.emit("clearChooses")
        BtnLoading.value = false;
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => {
          BtnLoading.value = false;
        }, 1500)
      }
    })
  }

  function HideVisible(row: FormInstance | undefined) {
    row.resetFields();
    Visible.value = false;
  }

  function handleSizeChange(row) {
    if (MySignIn.value !== 'all') {
      SelectDataById()
    } else {
      getListData(SetMyJSonar.value)
    }

  }

  function handleCurrentChange(row) {
    if (MySignIn.value !== 'all') {
      SelectDataById()
    } else {
      getListData(SetMyJSonar.value)
    }
  }

  // 通过确定摁钮去晒讯客户群  --但不会保存客户群
  async function getListData(row: any | string) {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      conditionsStr: (row == 'all' ? [] : row) || []
    };
    const res = await SecuritiesClientGetSecurityClients(data);
    if (res.success) {
      dataList.value = res.data.data;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 获取初始化列表数据
  async function getClientBaseData() {
    const data = {
      "planId": route.query.planId,
      "taskId": route.query.taskId
    }
    const res = await SecuritiesClientGetClientBaseData(data);
    if (res.success) {
      SelectCustomerBase.value = res?.data?.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 根据已保存客户群去搜索
  async function SelectDataById() {
    if (MySignIn.value == 'all') {
      emitter.emit("clearChooses")
    } else {
      const data = qs.stringify({
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        pageIndex: pagination.currentPage,
        pageCount: pagination.pageSize,
        clientBaseId: MySignIn.value
      });
      const res = await SecuritiesClientGetSecuritiesConditionDataById(data);
      if (res.success) {
        dataList.value = res.data.data;
        pagination.total = res.data.totalCount;
        riskGrade.value = res.data.riskGrade
        emitter.emit("ViewSecurities", res?.data?.conditionData || [])
      } else {
        ElMessage.error(res.msg)
      }
    }
  }

  // 清空选择的客户群
  emitter.on("clearChoose", () => {
    MySignIn.value = "all";
    SetMyJSonar.value = ""
    riskGrade.value = ""
    getListData(MySignIn.value);
  })

  onUnmounted(() => {
    emitter.off("ViewSecurities")
    emitter.emit("clearChooses")
  })

  onMounted(() => {
    getListData(MySignIn.value);
    getClientBaseData()
  })


  return {
    dataList,
    columns,
    loading,
    Visible,
    MySignIn,
    riskGrade,
    pagination,
    BtnLoading,
    CustomerGroup,
    RefScreenPerson,
    RefCustomerGroup,
    SelectCustomerBase,
    HideVisible,
    SelectDataById,
    handleSizeChange,
    getCustomerGroup,
    handleCurrentChange,
  }
}
